<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->

    <el-card>
      <!-- 头部提示 -->

      <el-alert
        title="消息提示的文案"
        type="info"
        center
        show-icon
        :closable="false"
      ></el-alert>

      <!-- 进度条区域 -->
      <el-steps
        :space="200"
        :active="active - 0"
        align-center
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tabs切换 -->

      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          v-model="active"
          :before-leave="beforeLeave"
          @tab-click="tabsChange"
        >
          <!-- 注意 : tabpane标签的父节点必须是 tabs -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>

            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>

            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>

            <!-- 级联选择器 -->

            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleCascaderChange"
              >
              </el-cascader>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品参数 -->
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTabledata"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  size="mini"
                  :label="cb"
                  v-for="(cb, index2) in item.attr_vals"
                  :key="index2"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <!-- 商品静态属性 -->

          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTableData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>

          <!-- 图片上传 -->
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片上传组件 -->
            <el-upload
              class="upload-demo"
              :action="UploadUrl"
              :headers="headers"
              :on-success="uploadSuccessFun"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>

          <!-- 商品内容 -->
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本输入框 -->

            <!-- bidirectional data binding（双向数据绑定） -->
            <quill-editor v-model="addForm.goods_introduce" ref="myQuillEditor">
            </quill-editor>

            <!-- 表单提交按钮 -->

            <el-button class="subBtn" type="primary" @click="addFormdata"
              >提交</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->

    <el-dialog title="图片预览" :visible.sync="imgboxVisiable" width="30%">
      <img class="previewImg" :src="serverPicPath" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { getdata } from "../../network/getdata";
import { uploadUrl } from "../../network/uploadUrl";
// 导入 lodash
import _ from "lodash";
export default {
  name: "add",
  data() {
    return {
      active: "0",
      // 表单对象
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        // 商品图片的临时路径
        pics: [],
        // 商品内容
        goods_introduce: "",
        // 动态属性和静态参数的数据
        attrs: [],
      },
      // 表单校验规则
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
      // 级联选择器配置对象
      cateProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
        checkStrictly: true,
      },
      // 从后台获取到的 商品分类列表
      cateList: [],
      // 动态参数列表
      manyTabledata: [],
      //静态属性列表
      onlyTableData: [],
      // 图片上传的Url
      UploadUrl: uploadUrl,
      // 图片上传请求头对象
      headers: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      //图片存放在服务器的真是地址
      serverPicPath: "",
      // 图片预览显示与隐藏
      imgboxVisiable: false,
    };
  },
  computed: {
    //获取商品分类的三级id
    getCateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
      return null;
    },
  },
  methods: {
    // 提交数据
    addFormdata() {
      //先对表单数据进行校验
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) {
          //表单数据不合法
          this.$message.error("请填写必填的数据");
          return;
        }

        //数据合法 --- 对 addForm中的 goods_cat 进行处理
        //因为 goods_cat 已经和级联选择器绑定 -- 所以需要把 addform 深拷贝处理进行处理
        let deepForm = _.cloneDeep(this.addForm);
        //将深拷贝的中 goods_cat 转换为 ',' 分割的字符串
        deepForm.goods_cat = deepForm.goods_cat.join(",");
        // console.log(deepForm)

        //处理动态参数
        this.manyTabledata.forEach((item) => {
          let temp = {};
          temp.attr_id = item.attr_id;
          temp.attr_value = item.attr_vals.join(" ");
          this.addForm.attrs.push(temp);
        });

        //处理静态参数
        this.onlyTableData.forEach((item) => {
          let temp = {};
          temp.attr_id = item.attr_id;
          temp.attr_value = item.attr_vals;
          this.addForm.attrs.push(temp);
        });
        deepForm.attrs = this.addForm.attrs;
        // console.log(deepForm)
        // 添加 发起请求 -- 商品名称必须是唯一的
        getdata({
          method: "post",
          url: "/goods",
          data: deepForm,
        }).then((result) => {
          const res = result.data;
          if (res.meta.status !== 201) {
            //添加失败
            this.$message.error("添加商品失败");
            return;
          }

          //添加成功
          this.$message.success("添加商品成功");
          this.$router.push("/goods");
        });
      });
    },
    // 图片移除
    handleRemove(file, fileList) {
      // 根据 file.response.data.tmp_path获取到返回的图片临时路径
      const filePath = file.response.data.temp_path;
      // 根据临时路径从 addForm.pics获取到对应的下标
      const index = this.addForm.pics.forEach((item) => {
        return item.pic === filePath;
      });
      // 使用 splice方法将对应的图片从 addForm.pics 中移除
      this.addForm.pics.splice(index, 1);
      console.log(this.addForm.pics);
    },
    // 图片预览
    handlePreview(file) {
      // console.log(file)
      // 通过 file 获取到图片存放在服务器的真实地址
      //将真实地址保存下来
      //煲图片显示在对话框中
      this.serverPicPath = file.response.data.url;
      this.imgboxVisiable = true;
    },
    // 图片上传成功的回调函数
    uploadSuccessFun(response, file, fileList) {
      const temp_path = response.data.tmp_path;
      const temp_path_Obj = {
        pic: temp_path,
      };
      this.addForm.pics.push(temp_path_Obj);
      console.log(this.addForm.pics);
    },
    //点击tabs切换
    tabsChange() {
      //通过判断当前的active来请求参数还是属性
      if (this.active === "1") {
        //请求商品动态参数
        getdata({
          method: "get",
          url: `categories/${this.getCateId}/attributes`,
          params: {
            sel: "many",
          },
        }).then((result) => {
          const res = result.data;
          if (res.meta.status !== 200) {
            //获取失败
            this.$message.error("获取动态参数失败");
            return;
          }
          //获取成功
          res.data.forEach((item) => {
            item.attr_vals = item.attr_vals.length
              ? item.attr_vals.split(",")
              : [];
          });
          this.manyTabledata = res.data;
          // console.log(this.manyTabledata)
        });
      } else if (this.active === "2") {
        //请求商品静态属性
        getdata({
          method: "get",
          url: `categories/${this.getCateId}/attributes`,
          params: {
            sel: "only",
          },
        }).then((result) => {
          const res = result.data;
          if (res.meta.status !== 200) {
            this.$message.error("获取商品静态属性失败");
            return;
          }
          //获取成功
          // console.log(res.data)
          this.onlyTableData = res.data;
        });
      }
    },
    //阻止还没选择分类就跳转
    beforeLeave(activeName, oldActiveName) {
      // console.log('即将要切换到的name值:'+activeName)
      // console.log('原来的name值:'+oldActiveName)
      if (oldActiveName === "0" && this.addForm.goods_cat.length !== 3) {
        //不能跳转,因为没有获取到请求商品参数必须的 商品分类 id
        this.$message.error("请先选择商品分类");
        return false;
      }
    },
    //监听级联选择器数值变化
    handleCascaderChange() {
      // console.log(this.addForm.goods_cat)
      //如果选中的不是第三级的分类,将选择框清空
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
        return;
      }
    },
    //获取商品分类列表
    getCateList() {
      getdata({
        method: "get",
        url: "/categories",
      }).then((result) => {
        const res = result.data;
        if (res.meta.status !== 200) {
          this.$message.error("获取分类列表失败");
          return;
        }
        //获取成功
        this.cateList = res.data;
      });
    },
  },
  created() {
    //获取商品分类列表
    this.getCateList();
  },
};
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
.previewImg {
  width: 100%;
}

.subBtn {
  margin-top: 15px;
}
</style>